<template>
  <el-card class="bg">
    <el-card class="main" v-if="userName && isSend">
      <h2>聊天室</h2>
      <ul class="msg-content" ref="aaa">
        <li
          v-for="(msg, index) in msgList"
          :key="index"
          :class="{ mine: msg.type === 'mine', sys: msg.type === 'sys' }"
        >
          <div>
            <span>{{ msg.username }}</span> : {{ msg.time }}
          </div>
          <div>{{ msg.value }}</div>
        </li>
      </ul>
      <el-form @submit.prevent="formSubmit">
        <el-form-item>
          <el-input
            type="textarea"
            rows="4"
            v-model="msgRef"
            @keydown.prevent.enter="formSubmit"
          ></el-input>
        </el-form-item>
        <el-button type="primary" @click="formSubmit">发送</el-button>
      </el-form>
    </el-card>
    <el-card v-else>
      <el-input placeholder="请输入用户名" v-model="userName" />
      <br />
      <br />
      <el-button type="primary" @click="loginChat">登录</el-button>
    </el-card>
  </el-card>
</template>

<script lang="ts">
export default {
  name: 'WeChat',
}
</script>

<script lang="ts" setup>
import { io } from 'socket.io-client'
import { ref } from 'vue'
import dayjs from 'dayjs'

interface Message {
  type: string
  value: string
  username?: string
  time?: string
}

const msgRef = ref()
const msgList = ref<Message[]>([])
const socket = io('ws://39.108.168.18:8080')
const aaa = ref()
const userName = ref('')
const isSend = ref(false)
const loginChat = () => {
  isSend.value = true
  // 发送用户名
  socket.emit('userName', userName.value)
}

const formSubmit = () => {
  // 发送消息
  if (!msgRef.value) return
  socket.emit('chat message', { value: msgRef.value })
  const data = {
    value: msgRef.value,
    type: 'mine',
    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    username: userName.value,
  }
  msgList.value.push(data)
  msgRef.value = ''
  aaa.value.scrollTop = aaa.value.scrollHeight - 290
  console.dir(aaa.value)
}

socket.on('chat message', (msg) => {
  // 接收到消息
  const data = {
    ...msg,
    type: 'others',
    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  }
  msgList.value.push(data)
  console.dir(aaa.value)
})

socket.on('someComming', (msg) => {
  // 有人进来了
  const data = {
    value: msg,
    type: 'sys',
    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  }
  msgList.value.push(data)
})
socket.on('someGo', (msg) => {
  // 有人走了
  const data = {
    value: msg,
    type: 'sys',
    time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  }
  msgList.value.push(data)
})
</script>

<style scoped>
.bg {
  background-color: #eee;
}
.main {
  width: 1000px;
  background-color: #fff;
  margin: 0 auto;
}
.msg-content {
  height: 350px;
  background-color: #eee;
}
ul {
  padding: 20px;
  overflow: auto;
}
li {
  list-style-type: none;
  line-height: 30px;
}
.mine {
  text-align: right;
}
.sys {
  text-align: center;
  color: #ccc;
}
</style>
